#include "ConcurrentAlloc.hpp"
#include <thread>
#include <vector>
#include <unistd.h>

// 该文件是一个测试文件

//ThreadCache申请空间测试
void Alloc1()
{
    for (int i = 0; i < 5; i++)
    {
        ConcurrentAlloc(6);
    }
}

void Alloc2()
{
    for(int i = 0; i < 5; i++)
    {
        ConcurrentAlloc(7);
    }
}

void AllocTest()
{
    std::thread t1(Alloc1);
    std::thread t2(Alloc2);

    t1.join();
    sleep(1);
    t2.join();
}

//该项目申请空间测试
void ConcurrentAllocTest1()
{
    void* ptr1 = ConcurrentAlloc(5);
    cout << ptr1 << endl;
    void* ptr2 = ConcurrentAlloc(8);
    cout << ptr2 << endl;
    void* ptr3 = ConcurrentAlloc(4);
    cout << ptr3 << endl;
    void* ptr4 = ConcurrentAlloc(6);
    cout << ptr4 << endl;
    void* ptr5 = ConcurrentAlloc(3);
    cout << ptr5 << endl;
}

void ConcurrentAllocTest2()
{
    for(int i = 0; i < 1024; i++)
    {
        void* ptr = ConcurrentAlloc(5);
        cout << "i: " << i << " " << ptr << endl;
    }

    void* ptr = ConcurrentAlloc(3);
    cout << "-------" << ptr << endl;
}

//释放空间测试
void ConcurrentFreeTest1()
{
    void* ptr1 = ConcurrentAlloc(5);
    void* ptr2 = ConcurrentAlloc(8);
    void* ptr3 = ConcurrentAlloc(4);
    void* ptr4 = ConcurrentAlloc(6);
    void* ptr5 = ConcurrentAlloc(3);
    void* ptr6 = ConcurrentAlloc(3);
    void* ptr7 = ConcurrentAlloc(3);//这时候刚好达到触发CentralCache向PageCache归还空间的条件


    cout << ptr1 << endl;
    cout << ptr2 << endl;
    cout << ptr3 << endl;
    cout << ptr4 << endl;
    cout << ptr5 << endl;

    ConcurrentFree(ptr1/*, 5*/);
    ConcurrentFree(ptr2/*, 8*/);
    ConcurrentFree(ptr3/*, 4*/);
    ConcurrentFree(ptr4/*, 6*/);
    ConcurrentFree(ptr5/*, 3*/);
    ConcurrentFree(ptr6/*, 3*/);
    ConcurrentFree(ptr7/*, 3*/);
}

//多线程测试
void MultiThreadAlloc1()
{
    std::vector<void*> v;

    for(int i = 0; i < 7; i++)//7次刚好能触发CentralCache向PageCache返回空间
    {
        void* ptr = ConcurrentAlloc(6);//每次都申请8b的空间
        v.push_back(ptr);
    }

    for(auto i: v)
    {
        ConcurrentFree(i/*, 6*/);
    }
}

void MultiThreadAlloc2()
{
    std::vector<void*> v;
    for(int i = 0; i < 7; i++)
    {
        void* ptr = ConcurrentAlloc(16);//每次都申请8b的空间
        v.push_back(ptr);
    }

    for(auto i: v)
    {
        ConcurrentFree(i/*, 16*/);
    }
}

void MultiThreadTest()
{
    std::thread t1(MultiThreadAlloc1);
    t1.join();
    std::thread t2(MultiThreadAlloc2);
    t2.join();
}


//大空间申请测试
void BigAlloc()
{
    void* p1 = ConcurrentAlloc(257*1024);//向PageCache获取空间
    ConcurrentFree(p1/*, 257*1024*/);

    void* p2 = ConcurrentAlloc(129*8*1024);//向OS获取空间
    ConcurrentFree(p2/*, 129*8*1024*/);
}

int main()
{
    // AllocTest();
    // ConcurrentAllocTest1();
    // ConcurrentAllocTest2();
    ConcurrentFreeTest1();
    // MultiThreadTest();
    // BigAlloc();

    return 0;
}